var jwt = require("jsonwebtoken")
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10); //加盐
module.exports = async (resquest,response)=>{
    var url = resquest.url; //path?query#hash
    var path = url.split("?")[0];
    var method = resquest.method;
	
	//允许跨域
	//cors处理跨域
	response.setHeader("Access-Control-Allow-Origin","*");

	if(path === "/api/users/register"  && method === "POST"){
		//获取到postman传递来的数据
		var bodyObj = await new Promise((reslove,reject)=>{
			var body = "";
			resquest.on("data",(data)=>{
				body += data.toString()
			})
			resquest.on("end",()=>{
				var bodyObj = JSON.parse(body);
				reslove(bodyObj)
			})
		})
		var {username,password} = bodyObj;
		
		//判断用户名是否已经被注册
		var sql = `select id from users where username='${username}'`;
		var results = await new Promise((reslove,reject)=>{
			global.connection.query(sql, (error, results) =>{
				if(error){
					reject(error)
				}else{
					reslove(results)
				}
			});
		})
		if(results.length > 0){
			//用户名已经被注册了！！！
			return {
				message:"username has been registered",
				data:"error"
			}
		}
		
		//将密码进行加密
		password = bcrypt.hashSync(password, salt);
		
		//拼sql 执行sql 进行注册操作
		var sql = `insert into users (username,password) values ('${username}','${password}')`;
		
		var data = await new Promise((reslove,reject)=>{
			global.connection.query(sql, (error, results) =>{
				if(error){
					reject(error)
				}else{
					reslove(results)
				}
			});
		})
		
		return {
		    message:"/api/blog/register",
			data:data
		};
	}

    if(path === "/api/users/login"  && method === "POST"){
		//1. 拿postman传递来的数据（用户名 密码）
		//注意点 此时的密码是明文的 数据库中存的是加密的
		var bodyObj = await new Promise((reslove,reject)=>{
			var body = "";
			resquest.on("data",(data)=>{
				body += data.toString()
			})
			resquest.on("end",()=>{
				var bodyObj = JSON.parse(body);
				reslove(bodyObj)
			})
		})
		var {username,password} = bodyObj;
		
		//2. 判断数据库中是否有这个用户
		var sql = `select password from users where username='${username}'`;
		var results = await new Promise((reslove,reject)=>{
			global.connection.query(sql, (error, results) =>{
				if(error){
					reject(error)
				}else{
					reslove(results)
				}
			});
		})
		if(results.length === 0){
			//用户未被注册了！！！
			return {
				message:"The user is not registered",
				data:"error"
			}
		}
		
		//3. 如果用户存在 则需要校验密码
		// hash : 数据库中存的加密的密码
		var hash = results[0].password;
		var flag = bcrypt.compareSync(password, hash);
		if(flag === false){
			//密码有误
			return {
				message:"wrong password",
				data:"error"
			}
		}
		
		//生成登录令牌并返回
		var token = jwt.sign({username:username},"damulovezdy",
					{ expiresIn: 60 * 60 * 24 * 7})

		//将token种在cookie中
		response.setHeader("Set-Cookie",`token=${token};path=/`)				
        return {
            message:"/api/blog/login",
			data:token
        };
    }
}